package com.daffodil.storage.config;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import com.daffodil.storage.properties.StorageProperties;
import com.daffodil.storage.properties.TencentProperties;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.TransferManagerConfiguration;

/**
 * 
 * @author yweijian
 * @date 2022年12月8日
 * @version 2.0.0
 * @description
 */
@Component
@Configuration
@ConditionalOnProperty(name = StorageProperties.NAME, havingValue = StorageProperties.TENCENT)
public class TencentClientConfig {

    @Bean
    @ConditionalOnMissingBean
    public COSClient cosClient(StorageProperties storageProperties) {
        TencentProperties properties = storageProperties.getTencent();
        COSCredentials credentials = new BasicCOSCredentials(properties.getAccessKey(), properties.getSecretKey());
        // 设置bucket的区域
        ClientConfig clientConfig = new ClientConfig(new Region(properties.getRegion()));
        // 生成cos客户端
        COSClient cosClient = new COSClient(credentials, clientConfig);
        return cosClient;
    }

    @Bean
    @ConditionalOnMissingBean
    public TransferManager transferManager(StorageProperties storageProperties, COSClient cosClient) {
        TencentProperties properties = storageProperties.getTencent();
        ExecutorService threadPool = Executors.newFixedThreadPool(properties.getThreadPoolSize());
        TransferManager transferManager = new TransferManager(cosClient, threadPool);
        
        TransferManagerConfiguration configuration = new TransferManagerConfiguration();
        configuration.setMinimumUploadPartSize(properties.getMinimumUploadPartSize());
        configuration.setMultipartCopyPartSize(properties.getMultipartCopyPartSize());
        configuration.setMultipartCopyThreshold(properties.getMultipartCopyThreshold());
        configuration.setMultipartUploadThreshold(properties.getMultipartUploadThreshold());
        
        transferManager.setConfiguration(configuration);
        return transferManager;
    }

}
